package cn.itcast.test.kafka;

import org.apache.kafka.clients.producer.*;
import org.junit.Test;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class ProducerQuickStart {

    @Test
    public void sendMsg() throws ExecutionException, InterruptedException {
        //2. 完成kafka的配置
        Properties properties = new Properties();
        //2.1 配置kafka的ip和端口
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "42.193.102.62:9092");

        //2.2 配置key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //2.3 配置value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //1. 创建生产者的核心对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3. 发送消息
        for (int i=0; i<5; i++){
            ProducerRecord<String, String> recod = new ProducerRecord<String, String>("itcast-topic-input", "hello", "hell world itcast");
            RecordMetadata recordMetadata = producer.send(recod).get();
            System.out.println(recordMetadata.offset());
        }


        //4. 关闭连接
        producer.close();
    }

    @Test
    public void sendMsgAsync() throws ExecutionException, InterruptedException {
        //2. 完成kafka的配置
        Properties properties = new Properties();
        //2.1 配置kafka的ip和端口
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "42.193.102.62:9092");

        //2.2 配置key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //2.3 配置value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        properties.put(ProducerConfig.ACKS_CONFIG, "all");

        properties.put(ProducerConfig.RETRIES_CONFIG, 10);

        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "gzip");

        //1. 创建生产者的核心对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3. 发送消息
        for (int i=0; i<100; i++){
            ProducerRecord<String, String> recod = new ProducerRecord<String, String>("order", "hello", "world" + i);
            producer.send(recod, new Callback() {
                @Override
                public void onCompletion(RecordMetadata metadata, Exception e) {
                    if(e != null){
                        e.printStackTrace();
                    }

                    System.out.println(metadata.offset());
                }
            });
        }


        //4. 关闭连接
        producer.close();
    }
}
